import logging
import logging.handlers
import os

from queue import Queue


class Logs:
    def __init__(self, cls_name):
        self.log_queue = Queue()
        log_path = os.path.join(os.getcwd(), 'run.log')
        log_format = logging.Formatter(
            '[%(asctime)-15s %(levelname)s %(name)s '
            '%(lineno)d %(process)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

        file_handler = logging.FileHandler(log_path)
        file_handler.setFormatter(log_format)
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(log_format)

        queue_listener = logging.handlers.QueueListener(self.log_queue,
                                                        file_handler,
                                                        stream_handler)
        queue_listener.start()

        queue_handler = logging.handlers.QueueHandler(self.log_queue)
        logger = logging.getLogger(cls_name)
        logger.setLevel(logging.INFO)
        logger.addHandler(queue_handler)
        self.log = logger

    def __del__(self):
        self.log_queue.put_nowait(None)
        self.log.handlers[0].close()

    def info(self, msg, *args):
        self.log.info(msg, *args)

    def error(self, msg, *args):
        self.log.level = logging.ERROR
        self.log.error(msg, *args)

    def warnning(self, msg, *args):
        self.log.level = logging.WARNING
        self.log.warning(msg, *args)

    def debug(self, msg, *args):
        self.log.level = logging.DEBUG
        self.log.debug(msg, *args)

    def critical(self, msg, *args):
        self.log.level = logging.CRITICAL
        self.log.critical(msg, *args)
